
# Uncomment the custom TEST_RUNNER and COVERAGE_MODULES
# assignements in settings.py to run the code coverage test.

import coverage

from django.conf import settings
from django.test.simple import run_tests as django_test_runner


def test_runner_with_coverage(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """Custom test runner. Follows the django.test.simple.run_tests() interface."""
    
    if not getattr(settings, "COVERAGE_MODULES", False):
        raise Exception("Define COVERAGE_MODULES in your settings file. Refer to the django-contract documentation for more help.")

    coverage.use_cache(0) # Do not cache any of the coverage.py stuff
    coverage.start()
    
    import django_contract
    django_contract.contract_enable()
    
    test_results = django_test_runner(test_labels, verbosity, interactive, extra_tests)

    coverage.stop()

    print ''
    print '------------------------------------------------------------------'
    print ' Code Coverage Results'
    print '------------------------------------------------------------------'

    coverage_modules = []
    for module in settings.COVERAGE_MODULES:
        coverage_modules.append(__import__(module, globals(), locals(), ['']))

    coverage.report(coverage_modules, show_missing=1)

    print '------------------------------------------------------------------'
    return test_results

